﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Deeper.Common
{
	public class LazyQueue<T>
	{
		public LazyQueue(Action<T> handler, int inteval, int onecount)
		{
			_handler = handler;
			_inteval = inteval;
			_onecount = onecount;
			_t = new Thread(ThreadProc);
			_t.Name = "LazyQueue";
			_t.IsBackground = true;
		}
		public void EnQueue(T item)
		{
			lock (_queue)
			{
				_queue.Enqueue(item);
			}
		}
		public void Start()
		{
			_t.Start();
		}

		private void ThreadProc(object state)
		{
			while (true)
			{
				try
				{
					List<T> tempItems = new List<T>(_onecount);
					lock (_queue)
					{
						for (int i = _onecount - 1; i >= 0; i--)
						{
							if (_queue.Count > 0)
							{
								tempItems.Add(_queue.Dequeue());
							}
						}
					}
					tempItems.ForEach(_handler);

				}
				catch (Exception ex)
				{
					System.Diagnostics.Trace.TraceError("ThreadProc error:{0}", ex);
				}

				Thread.Sleep(_inteval);
			}
		}

		private Queue<T> _queue = new Queue<T>();
		private Action<T> _handler = null;
		private int _inteval = 0;
		private int _onecount = 0;
		private Thread _t = null;
	}
}
